/**
 * Created by DevilsEyes on 2016/6/9.
 */
'use strict';

let focus = null,
    f = 0,
    w = 0,
    h = 0;

class Point {
    constructor(x, y, z) {
        this.init = {
            x: x,
            y: y,
            z: z
        };

        this.x = x;
        this.y = y;
        this.z = z;

        this.tx = x;
        this.ty = y;
        this.tz = z;

    }

    get r() {
        let dx = this.tx - focus.x;
        let dy = this.ty - focus.y;
        let dz = this.tz - focus.z;
        return Math.sqrt(dx * dx + dy * dy + dz * dz);
    }

    toCamera() {
        let {abs} = Math;

        return {
            h: this.tz * f / abs(this.tx - focus.x),
            v: this.ty * f / abs(this.tx - focus.x),
            r: this.r
        }
    }

    toCanvas() {
        let p = this.toCamera();
        return {
            x: w / 2 + p.v,
            y: h / 2 + p.h
        }
    }

    turnX(a) {
        a = -a;
        this.tx = this.x * Math.cos(a) + this.y * Math.sin(a);
        this.ty = -this.x * Math.sin(a) + this.y * Math.cos(a);
        this.tz = this.z;
    }

    turnY(a) {
        a = -a;
        this.tx = this.x * Math.cos(a) + this.z * Math.sin(a);
        this.ty = this.y;
        this.tz = -this.x * Math.sin(a) + this.z * Math.cos(a);
    }

    move(x,y,z){
        this.tx += x;
        this.ty += y;
        this.tz += z;
    }

    save() {
        this.x = this.tx;
        this.y = this.ty;
        this.z = this.tz;
    }

    refresh() {
        this.x = this.init.x;
        this.y = this.init.y;
        this.z = this.init.z;
    }
}

module.exports = {

    Point,//构造函数

    //初始化函数
    init: (config)=> {
        w = config.canvasWidth;
        h = config.canvasHeight;
        f = config.focalLength;
        focus = config.focus;
    },

    //配置项
    getConfigs() {
        return {
            canvasWidth: w,
            canvasHeight: h,
            focalLength: f,
            focus: focus
        }
    },

//==============快捷方法===================
    //快速创建
    P: (x, y, z)=>new Point(x, y, z),

    //获取焦点
    focus
};